package com.tanhua.dubbo.api.impl;
import org.bson.types.ObjectId;

import com.tanhua.domain.mongo.Answer;
import com.tanhua.domain.mongo.Soul;
import com.tanhua.domain.mongo.SoulTest;
import com.tanhua.domain.mongo.UserConclusion;
import com.tanhua.dubbo.api.SoulApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class SoulApiImpl implements SoulApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    private final String Answers = "answer_";

    //测灵魂-问卷列表
    @Override
    public List<Soul> findAllSoul() {

        List<Soul> soulList = mongoTemplate.find(new Query(), Soul.class);
        return soulList;
    }

    //测灵魂-提交问卷
    @Override
    public void save(Answer answer, Long userId) {

        mongoTemplate.save(answer, Answers + answer.getQuestionId() + "_" + userId);
    }

    //如果存在就删除用户问卷答案表
    @Override
    public void remove(String question, Long userId) {
        if (mongoTemplate.exists(new Query(), Answers + question + "_" + userId)) {
            mongoTemplate.dropCollection(Answers + question + "_" + userId);
        }
    }

    //查询第几套卷子
    @Override
    public Soul find(String questionId) {
        Query query = new Query(Criteria.where("question_Id").is(questionId));
        Soul soul = mongoTemplate.findOne(query, Soul.class);
        return soul;
    }

    @Override
    public List<Answer> findByIdToAnswer(Long userId, String id) {

        List<Answer> answerList = mongoTemplate.find(new Query(), Answer.class, Answers + id + userId);

        return answerList;
    }

    //添加用户性格
    public void saveUserConclusion(UserConclusion userConclusion) {
        mongoTemplate.save(userConclusion);
    }

    //查询相同性格的用户id
    @Override
    public List<Long> queryUserIdByConclusion(String conclusions) {
        Query query = new Query(Criteria.where("conclusion").is(conclusions));
        List<UserConclusion> conclusionList = mongoTemplate.find(query, UserConclusion.class);
        List<Long> userIdList = new ArrayList<>();
        if(conclusionList!=null){
            for (UserConclusion conclusion : conclusionList) {
                userIdList.add(conclusion.getUserId());
            }
        }
        return userIdList;
    }

    //查询用户性格
    public String findUserConclusions(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserConclusion conclusion = mongoTemplate.findOne(query, UserConclusion.class);
        return conclusion.getConclusion();
    }
}
